package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConst;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;
import service.SetmealService;

import java.util.List;

/**
 * ClassName: SetmealServiceImpl
 * Description:套餐业务实现类
 * date: 2019/11/22 14:51
 * Author Airson
 * Since JDK 1.8
 */

@Service
public class SetmealServiceImpl implements SetmealService {

    //依赖注入
    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;

    /**
     * 添加套餐表单数据
     * 维护套餐和检查组之间的关系(在中间表添加数据)
     *
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //调用dao添加方法并返回套餐id
        setmealDao.add(setmeal);
        //获取图片文件名
        String imgname = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_DB_RESOURCES, imgname);
        //遍历判断
        if (setmeal.getId() != null && checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                //维护关系,在中间表添加数据
                setmealDao.set(setmeal.getId(), checkgroupId);
            }
        }
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    @Transactional
    public PageResult findPage(QueryPageBean queryPageBean) {

        //开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //条件查询
        Page<Setmeal> page = setmealDao.queryPage(queryPageBean.getQueryString());
        //返回结果
        return new PageResult(page.getTotal(), page);
    }

    /**
     * 查询所有套餐
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }
}
